package com.yitao.cms.service.user.cmsUser;



import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.skipper.base.bean.CommonStatus;
import com.skipper.base.bean.DataOutput;
import com.skipper.base.service.GenericEntityService;
import com.yitao.client.constant.BaseConstant;
import com.yitao.cms.constant.UserErrorEnum;
import com.yitao.cms.constant.UserSession;
import com.yitao.cms.dto.operationUser.OperationPermissionDto;
import com.yitao.cms.enums.PermissionEnums;
import com.yitao.cms.enums.UserStateEnums;
import com.yitao.cms.model.operationUser.OperationPermissionModel;
import com.yitao.cms.model.operationUser.OperationRolePermissionModel;
import com.yitao.cms.model.operationUser.QOperationPermissionModel;
import com.yitao.cms.model.operationUser.QOperationRolePermissionModel;
import com.yitao.cms.utils.BaseUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;


@Service
public class OperationPermissionService extends GenericEntityService<OperationPermissionModel, OperationPermissionDto, QOperationPermissionModel> {
    public OperationPermissionService(EntityManager entityManager) {
        super(entityManager);
    }

    private BaseUtils base = BaseUtils.getInstance();
    /**
     * 资源添加
     *
     * @param
     * @return
     */
    @Transactional
    public DataOutput updatePermission(OperationPermissionDto permissionDto, HttpServletRequest request) {
        logger.info("资源添加入参:{}" + permissionDto.toString());
        try {
            OperationPermissionModel permission = new OperationPermissionModel();
            BeanUtils.copyProperties(permissionDto,permission);
            if (permissionDto!=null && permissionDto.getId()!=null){
                OperationPermissionModel operationPermissionModel =queryFactory.select(Q).from(Q).where(Q.id.eq(permissionDto.getId())).fetchFirst();
                if (operationPermissionModel!=null){
                    permission.setCreateBy(operationPermissionModel.getCreateBy());
                    permission.setCreateTime(operationPermissionModel.getCreateTime());
                    permission.setParentId(operationPermissionModel.getParentId());
                    permission.setState(operationPermissionModel.getState());
                    permission.setIsDelete(operationPermissionModel.getIsDelete());
                    permission.setPathType(operationPermissionModel.getPathType());
                    permission.setLastUpdateBy(UserSession.getUserIdBySession(request));
                    permission.setLastUpdateTime(base.getNow());
                }else {
                    return new DataOutput(CommonStatus.BAD_REQUEST);
                }
            }else{
                if (permissionDto.getParentId()==null){
                    permission.setParentId(0L);
                }
                if (null==permission.getPathType()) {
                    permission.setPathType(PermissionEnums.pathType.SUBMENU.getCode());//默认子菜单
                }
                permission.setIsDelete(UserStateEnums.deleteStateEnum.NO.getCode());
                permission.setState(UserStateEnums.UserStateEnum.ENABLE.getCode());
                permission.setCreateBy(UserSession.getUserIdBySession(request));
                permission.setCreateTime(base.getNow());
            }
            repository.save(permission);
            if (PermissionEnums.pathType.SUBMENU.getCode().equals(permission.getPathType())) {
                if (permission.getParentId()!=null && permission.getParentId()!=0L) {
                    repository.updateByWhere(Q.id.eq(permission.getParentId()),
                            it -> it.set(Q.pathType, PermissionEnums.pathType.PARENT_MENU.getCode()));
                }
            }
            return new DataOutput<>(CommonStatus.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("资源添加 执行异常{}" + e.getMessage());
            return new DataOutput<>(CommonStatus.BAD_REQUEST.getCode(), CommonStatus.SERVER_ERROR.getMessage());

        }
    }
    //查找用户的菜单
  public List<OperationPermissionModel> getListByParentId(Long parentId, List<String> PermissionIdList,Integer status) {
        //获取父菜单
      List<OperationPermissionModel> permissions = new ArrayList<>();
      if (UserStateEnums.UserStateEnum.ENABLE.getCode().equals(status)) {
          permissions = repository.findAll(Q.parentId.eq(parentId).and(Q.state.eq(status)),new OrderSpecifier<>(Order.ASC, Q.sort) );
      } else {
          permissions = repository.findAll(Q.parentId.eq(parentId));
      }
        if (PermissionIdList == null) {
            return permissions;
        }
        List<OperationPermissionModel> userPermissions = new ArrayList<>();
        for (OperationPermissionModel permission : permissions) {
            convertEntityToDto(permission);
            if (PermissionIdList.contains(String.valueOf(permission.getId()))) {
                userPermissions.add(permission);
            }
        }
        return userPermissions;
    }

    //递归查询子菜单
   public List<OperationPermissionDto> getPermissionTreeList(List<OperationPermissionModel> permissions, List<String> permissionIdList,Integer status) {
        List<OperationPermissionDto> resultPermissionDto = new ArrayList<>();
        for (OperationPermissionModel permission : permissions) {
            //判断该资源是否为一个菜单
            OperationPermissionDto permissionDto = convertEntityToDto(permission);
            if (permission.getResourceType() == 0) {
                permissionDto.setChildren(
                        getPermissionTreeList(getListByParentId(permission.getId(), permissionIdList,status), permissionIdList,status));
            }
            resultPermissionDto.add(permissionDto);
        }
        return resultPermissionDto;
    }

    /**
     * 菜单禁用
     */
  @Transactional
    public DataOutput permissionDeleteById(Long permissionId) {
        logger.info("菜单禁用入参{}" + permissionId);
        try {
            OperationPermissionModel permission = queryFactory.select(Q).from(Q).where(Q.id.eq(permissionId)).fetchOne();
            if (permission == null) {
                return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "菜单不存在！");
            } else {//判断是否有子菜单
                List<OperationPermissionModel> permissions = repository.findAll(Q.parentId.eq(permission.getId()).and(Q.state.eq(UserStateEnums.UserStateEnum.ENABLE.getCode())));
                if (permissions==null||permissions.size()==0){
                    repository.updateByWhere(Q.id.eq(permissionId), it -> it
                            .set(Q.state, UserStateEnums.UserStateEnum.DISABLE.getCode()));
                    return new DataOutput(CommonStatus.SUCCESS);
                }else{
                    return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "请先删除子菜单！");
                }
            }
        } catch (Exception e) {
            logger.error("菜单删除 执行异常{}" + e.getMessage());
            return new DataOutput(CommonStatus.SERVER_ERROR);
        }
    }



    /**
     * 资源列表
     *
     * @return
     */
   public DataOutput permissionList() {
        try {
            List<OperationPermissionModel> permissions = repository.findAll(Q.parentId.eq(0L).and(Q.state.eq(UserStateEnums.UserStateEnum.ENABLE.getCode()))
                    ,new OrderSpecifier(Order.ASC, Q.sort));
         /*   getPermissionTreeList(permissions, null);*/
            logger.info("菜单列表出参{}：" + getPermissionTreeList(permissions, null,UserStateEnums.UserStateEnum.ENABLE.getCode()));
            return new DataOutput<>(getPermissionTreeList(permissions, null,UserStateEnums.UserStateEnum.ENABLE.getCode()));
        } catch (Exception e) {
            logger.info("资源列表 执行异常" + e.getMessage());
            return new DataOutput(CommonStatus.SERVER_ERROR);
        }
    }
}
